#include <stdio.h>
#include <unistd.h>
#include <iostream>

#include "LogicPool/LogicInterfaceUSB.h"
#include "LogicPool/DFM.h"

using namespace std;


LogicInterfaceUSB li("/dev/ttyUSB0");
DFM dfm(li);


void showLimits()
{
    uint8_t channel;

    cout << "limits: ";
    for (channel = 0; channel < 8; channel ++)
        printf("%6d", dfm.GetLimit(channel));
    cout << endl;
}


void showState()
{
    printf("alarm : %4x\n", (int)dfm.GetState());
}


int main(int argc, char **argv)
{
    uint8_t channel;
    int limit = 33;
    int id;
    
    li.Open();  
    cout << "LogicBox ID: " << hex << (id = dfm.GetID()) << endl;
    /* abort if we get the wrong ID */
    if (id != 2) {
    	cout << "ERROR: ID should be 2" << endl; 
    	exit(-2);
    }


    cout << endl <<"test 1: setting all limits to 0, 3s delay, resetting..." << endl;
    cout <<"(all output channels should stay active)" << endl;
    for (channel = 0; channel < 8; channel ++)
        dfm.SetLimit(channel, 0);
    dfm.SetReactionTime(3);
    dfm.Reset();
    cout << "waiting for 2 seconds..." << endl; 
    sleep(2);
    showLimits();
    showState();


    cout << endl << "test 2: setting all limits to " << dec << limit << ", 3s delay" << endl;
    cout <<"(all output channels should go inactive after three seconds)" << endl;
    for (channel = 0; channel < 8; channel ++)
        dfm.SetLimit(channel, limit);
    dfm.Reset();
    cout << "waiting for 5 seconds..." << endl; 
	sleep(5);
    showLimits();
    showState();


    cout << endl<< "test 3: setting all limits to 0; channel 0 to 250, resetting..." << endl;
    for (channel = 0; channel < 8; channel ++)
        dfm.SetLimit(channel, 0);
    dfm.SetLimit(0, 250);
    dfm.SetReactionTime(3);
    dfm.Reset();
    cout << "reading (raw) flow values" << endl;
    while (1) {
        sleep(1);
        cout << "flow: ";
        for (channel = 0; channel < 8; channel ++)
            cout << dfm.GetRate(channel) << " ";
        cout << "\t";
        showState();
    }

    li.Close();
    return 0;
}
